from fastapi import FastAPI, HTTPException, Depends
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from sqlite3 import Connection
from typing import List, Optional
import uvicorn
from datetime import datetime

from database import get_db
from schemas import JudgeCreate, ContestantCreate, ScoreCreate, ScoreResponse, ContestantResponse
from crud import (
    create_judge, get_judges, create_contestant, get_contestants, 
    create_score, get_scores_by_contestant, get_active_contestant,
    set_active_contestant, clear_judge_scores, get_all_scores_with_ranking,
    check_judge_score, get_judge_by_name, delete_judge, delete_contestant,
    get_active_contestant_with_adjusted_average
)

app = FastAPI(title="评委打分系统", version="1.0.0")

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")
# 挂载 Vite 构建产物的资源目录（dist/assets -> static/assets）
app.mount("/assets", StaticFiles(directory="static/assets"), name="assets")

@app.get("/", response_class=HTMLResponse)
def read_root():
    # 使用 SPA 的入口文件
    with open("static/index.html", "r", encoding="utf-8") as f:
        return HTMLResponse(content=f.read())

@app.get("/display", response_class=HTMLResponse)
def read_display():
    # 使用 SPA 的入口文件，由前端路由决定页面
    with open("static/index.html", "r", encoding="utf-8") as f:
        return HTMLResponse(content=f.read())

@app.get("/admin", response_class=HTMLResponse)
def read_admin():
    # 使用 SPA 的入口文件，由前端路由决定页面
    with open("static/index.html", "r", encoding="utf-8") as f:
        return HTMLResponse(content=f.read())

# API路由
@app.post("/api/judges/")
def create_judge_api(judge: JudgeCreate, db: Connection = Depends(get_db)):
    try:
        return create_judge(db=db, judge=judge)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器内部错误: {str(e)}")

@app.get("/api/judges/")
def get_judges_api(db: Connection = Depends(get_db)):
    return get_judges(db=db)

@app.post("/api/contestants/")
def create_contestant_api(contestant: ContestantCreate, db: Connection = Depends(get_db)):
    try:
        return create_contestant(db=db, contestant=contestant)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器内部错误: {str(e)}")

@app.get("/api/contestants/")
def get_contestants_api(db: Connection = Depends(get_db)):
    return get_contestants(db=db)

@app.get("/api/contestants/active")
def get_active_contestant_api(db: Connection = Depends(get_db)):
    return get_active_contestant(db=db)

@app.get("/api/contestants/active/adjusted-average")
def get_active_contestant_adjusted_average_api(db: Connection = Depends(get_db)):
    result = get_active_contestant_with_adjusted_average(db=db)
    if result is None:
        return {"contestant": None, "adjusted_average": 0.0, "total_scores": 0, "effective_score_count": 0}
    return result

@app.get("/api/judges/count")
def get_judges_count_api(db: Connection = Depends(get_db)):
    """获取评委总数"""
    cursor = db.cursor()
    cursor.execute("SELECT COUNT(*) as total_judges FROM judges")
    result = cursor.fetchone()
    return {"total_judges": result[0] if result else 0}

@app.post("/api/contestants/{contestant_id}/activate")
def activate_contestant_api(contestant_id: int, db: Connection = Depends(get_db)):
    success = set_active_contestant(db=db, contestant_id=contestant_id)
    if success:
        return {"message": "选手已激活"}
    else:
        raise HTTPException(status_code=404, detail="选手不存在")

@app.post("/api/scores/")
def create_score_api(score: ScoreCreate, db: Connection = Depends(get_db)):
    try:
        return create_score(db=db, score=score)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@app.get("/api/scores/contestant/{contestant_id}", response_model=List[ScoreResponse])
def get_scores_by_contestant_api(contestant_id: int, db: Connection = Depends(get_db)):
    return get_scores_by_contestant(db=db, contestant_id=contestant_id)

@app.get("/api/scores/ranking", response_model=List[ContestantResponse])
def get_ranking_api(db: Connection = Depends(get_db)):
    return get_all_scores_with_ranking(db=db)

@app.get("/api/scores/judge/{judge_id}/contestant/{contestant_id}/check")
def check_judge_score_api(judge_id: int, contestant_id: int, db: Connection = Depends(get_db)):
    has_scored = check_judge_score(db=db, judge_id=judge_id, contestant_id=contestant_id)
    return {"has_scored": has_scored}

@app.delete("/api/scores/judge/{judge_name}/contestant/{contestant_id}")
def clear_judge_scores_by_name_api(judge_name: str, contestant_id: int, db: Connection = Depends(get_db)):
    # 通过评委姓名查找评委ID
    judge = get_judge_by_name(db=db, judge_name=judge_name)
    if not judge:
        raise HTTPException(status_code=404, detail="评委不存在")
    
    success = clear_judge_scores(db=db, judge_id=judge['id'], contestant_id=contestant_id)
    if success:
        return {"message": f"评委 {judge_name} 的评分已清空"}
    else:
        raise HTTPException(status_code=404, detail="评分记录不存在")

@app.delete("/api/scores/judge/{judge_id}/contestant/{contestant_id}")
def clear_judge_scores_api(judge_id: int, contestant_id: int, db: Connection = Depends(get_db)):
    success = clear_judge_scores(db=db, judge_id=judge_id, contestant_id=contestant_id)
    if success:
        return {"message": "评委打分已清空"}
    else:
        raise HTTPException(status_code=404, detail="评分记录不存在")

@app.delete("/api/judges/{judge_id}")
def delete_judge_api(judge_id: int, db: Connection = Depends(get_db)):
    """删除评委"""
    success = delete_judge(db=db, judge_id=judge_id)
    if success:
        return {"message": "评委删除成功"}
    else:
        raise HTTPException(status_code=404, detail="评委不存在或删除失败")

@app.delete("/api/contestants/{contestant_id}")
def delete_contestant_api(contestant_id: int, db: Connection = Depends(get_db)):
    """删除选手"""
    success = delete_contestant(db=db, contestant_id=contestant_id)
    if success:
        return {"message": "选手删除成功"}
    else:
        raise HTTPException(status_code=404, detail="选手不存在或删除失败")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000) 